package com.sunbim.rsrv.util.common;

import cn.hutool.core.util.NumberUtil;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;

public class SortUtil {


    public static <T> List<T> sorted(List<T> originList, Map<String, List<String>> orderVals) {
        try {
            List<DomainWrapper> wrapperList = new ArrayList<>();
            for (T t : originList) {
                int order = 0;
                int index = orderVals.size();
                Iterator<Map.Entry<String, List<String>>> iterator = orderVals.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, List<String>> next = iterator.next();
                    String filedName = next.getKey();
                    List<String> orderList = next.getValue();
                    //反射获取T的属性值
                    Field field = t.getClass().getDeclaredField(filedName);
                    field.setAccessible(true);
                    String val = (String) field.get(t);
                    order += NumberUtil.pow(10, index).multiply(new BigDecimal(getOrder(val, orderList))).longValue();
                    index--;
                }
                //包装成DomainWrapper集合
                wrapperList.add(new DomainWrapper<T>().setDomain(t).setOrder(order));
            }

            //按照order排序,排好序按顺序取出T，放入集合
            List<T> tList = new ArrayList<>();
            List<T> finalTList = tList;
            wrapperList.stream()
                    .sorted(Comparator.comparingInt(DomainWrapper::getOrder))
                    .forEach(e -> finalTList.add((T) e.getDomain()));
            //返回
            return tList;
        } catch (Exception e) {
            e.printStackTrace();
            return originList;
        }

    }

    private static int getOrder(String val, List<String> orderVals) throws Exception {
        for (int i = 0; i < orderVals.size(); i++) {
            if (val.contains(orderVals.get(i))) {
                return i;
            }
        }
        // 不在排序规则中的往后排
        return orderVals.size() + 1;
    }

    static class DomainWrapper<T> {
        private T domain;
        private int order;//顺序

        public T getDomain() {
            return domain;
        }

        public DomainWrapper<T> setDomain(T domain) {
            this.domain = domain;
            return this;
        }

        public int getOrder() {
            return order;
        }

        public DomainWrapper<T> setOrder(int order) {
            this.order = order;
            return this;
        }
    }

    public static void main(String[] args) {

    }
}

